/**
 * V2解析视图组件
 */
class V2ResolveView {
    constructor(route) {
        this.route = route;
        this.title = route.title || 'V2解析';
        this.chart = null;
        this.historyTable = null;
        this.latencyChart = null;
        this.successChart = null;
    }
    
    /**
     * 渲染页面内容
     */
    async render() {
        return `
            <div class="layui-fluid content-wrapper">
                <div class="content-header">
                    <h2>V2解析</h2>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md8">
                        <div class="layui-card">
                            <div class="layui-card-header">V2解析配置</div>
                            <div class="layui-card-body">
                                <form class="layui-form" lay-filter="v2-resolve-form">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">解析类型</label>
                                        <div class="layui-input-block">
                                            <input type="radio" name="resolveType" value="vmess" title="VMess" checked>
                                            <input type="radio" name="resolveType" value="vless" title="VLESS">
                                            <input type="radio" name="resolveType" value="trojan" title="Trojan">
                                            <input type="radio" name="resolveType" value="shadowsocks" title="Shadowsocks">
                                        </div>
                                    </div>
                                    
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">服务器地址</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="serverAddress" required lay-verify="required" placeholder="请输入服务器地址" class="layui-input">
                                        </div>
                                    </div>
                                    
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">端口</label>
                                        <div class="layui-input-block">
                                            <input type="number" name="serverPort" required lay-verify="required" placeholder="请输入端口号" class="layui-input">
                                        </div>
                                    </div>
                                    
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">用户ID</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="userId" required lay-verify="required" placeholder="请输入用户ID" class="layui-input">
                                        </div>
                                    </div>
                                    
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">额外ID</label>
                                        <div class="layui-input-block">
                                            <input type="number" name="alterId" value="0" placeholder="请输入额外ID" class="layui-input">
                                        </div>
                                    </div>
                                    
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">传输协议</label>
                                        <div class="layui-input-block">
                                            <select name="transport" lay-filter="transport-filter">
                                                <option value="tcp">TCP</option>
                                                <option value="ws">WebSocket</option>
                                                <option value="kcp">KCP</option>
                                                <option value="quic">QUIC</option>
                                                <option value="grpc">gRPC</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="layui-form-item" id="ws-path-group" style="display: none;">
                                        <label class="layui-form-label">WebSocket路径</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="wsPath" value="/ws" placeholder="请输入WebSocket路径" class="layui-input">
                                        </div>
                                    </div>
                                    
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">TLS</label>
                                        <div class="layui-input-block">
                                            <input type="checkbox" name="tls" lay-skin="switch" lay-text="开启|关闭">
                                        </div>
                                    </div>
                                    
                                    <div class="layui-form-item">
                                        <div class="layui-input-block">
                                            <button class="layui-btn" lay-submit lay-filter="resolve-btn">
                                                <i class="layui-icon layui-icon-ok"></i> 开始解析
                                            </button>
                                            <button class="layui-btn layui-btn-primary" lay-filter="test-btn">
                                                <i class="layui-icon layui-icon-release"></i> 测试连接
                                            </button>
                                            <button class="layui-btn layui-btn-normal" lay-filter="copy-btn">
                                                <i class="layui-icon layui-icon-template"></i> 复制配置
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-col-md4">
                        <div class="layui-card">
                            <div class="layui-card-header">解析结果</div>
                            <div class="layui-card-body">
                                <div id="resolve-result" class="resolve-result">
                                    <div class="result-placeholder">
                                        <i class="layui-icon layui-icon-engine"></i>
                                        <p>等待解析...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md12">
                        <div class="layui-card">
                            <div class="layui-card-header">解析统计</div>
                            <div class="layui-card-body">
                                <div id="resolveChart" style="height: 300px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md6">
                        <div class="layui-card">
                            <div class="layui-card-header">响应时间分析</div>
                            <div class="layui-card-body">
                                <div id="latencyChart" style="height: 250px;"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-col-md6">
                        <div class="layui-card">
                            <div class="layui-card-header">成功率趋势</div>
                            <div class="layui-card-body">
                                <div id="successChart" style="height: 250px;"></div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md12">
                        <div class="layui-card">
                            <div class="layui-card-header">解析历史</div>
                            <div class="layui-card-body">
                                <table class="layui-table" id="historyTable" lay-filter="history-table">
                                    <thead>
                                        <tr>
                                            <th lay-data="{field:'time', width:150, sort:true}">时间</th>
                                            <th lay-data="{field:'server', width:200}">服务器</th>
                                            <th lay-data="{field:'type', width:100}">类型</th>
                                            <th lay-data="{field:'status', width:100}">状态</th>
                                            <th lay-data="{field:'latency', width:100, sort:true}">延迟(ms)</th>
                                            <th lay-data="{field:'result', width:200}">结果</th>
                                            <th lay-data="{field:'operation', width:120}">操作</th>
                                        </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 初始化组件
     */
    async init() {
        console.log('V2解析组件初始化');
        
        // 等待DOM加载
        await this.waitForDOM();
        
        // 初始化图表
        this.initCharts();
        
        // 初始化表格
        this.initTable();
        
        // 绑定事件
        this.bindEvents();
        
        // 加载历史数据
        this.loadHistoryData();
        
        // 使用LayUI渲染
        if (typeof layui !== 'undefined') {
            layui.use(['element', 'layer', 'table', 'form'], function() {
                var element = layui.element;
                var layer = layui.layer;
                var table = layui.table;
                var form = layui.form;
                
                element.render();
                form.render();
            });
        }
    }
    
    /**
     * 等待DOM加载
     */
    waitForDOM() {
        return new Promise((resolve) => {
            if (document.getElementById('resolveChart') && 
                document.getElementById('historyTable') &&
                document.getElementById('latencyChart') &&
                document.getElementById('successChart')) {
                resolve();
            } else {
                setTimeout(() => resolve(), 100);
            }
        });
    }
    
    /**
     * 初始化图表
     */
    initCharts() {
        // 初始化解析统计图表
        const resolveChartDom = document.getElementById('resolveChart');
        if (resolveChartDom) {
            this.chart = echarts.init(resolveChartDom);
            this.initResolveChart();
        }
        
        // 初始化延迟图表
        const latencyChartDom = document.getElementById('latencyChart');
        if (latencyChartDom) {
            this.latencyChart = echarts.init(latencyChartDom);
            this.initLatencyChart();
        }
        
        // 初始化成功率图表
        const successChartDom = document.getElementById('successChart');
        if (successChartDom) {
            this.successChart = echarts.init(successChartDom);
            this.initSuccessChart();
        }
    }
    
    /**
     * 初始化解析统计图表
     */
    initResolveChart() {
        if (!this.chart) return;
        
        const option = {
            title: {
                text: '解析统计',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: ['成功', '失败', '超时', '错误']
            },
            series: [
                {
                    name: '解析结果',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        {value: 335, name: '成功', itemStyle: {color: '#5FB878'}},
                        {value: 310, name: '失败', itemStyle: {color: '#FF5722'}},
                        {value: 234, name: '超时', itemStyle: {color: '#FFB800'}},
                        {value: 135, name: '错误', itemStyle: {color: '#FF5722'}}
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        
        this.chart.setOption(option);
    }
    
    /**
     * 初始化延迟图表
     */
    initLatencyChart() {
        if (!this.latencyChart) return;
        
        const option = {
            title: {
                text: '响应时间分析',
                left: 'center',
                textStyle: {
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: '{b}: {c} ms'
            },
            xAxis: {
                type: 'category',
                data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00'],
                axisLabel: {
                    fontSize: 10
                }
            },
            yAxis: {
                type: 'value',
                name: '延迟(ms)',
                nameTextStyle: {
                    fontSize: 10
                },
                axisLabel: {
                    fontSize: 10
                }
            },
            series: [{
                name: '延迟',
                type: 'line',
                data: [120, 132, 101, 134, 90, 230],
                smooth: true,
                itemStyle: {
                    color: '#009688'
                },
                lineStyle: {
                    width: 2
                }
            }]
        };
        
        this.latencyChart.setOption(option);
    }
    
    /**
     * 初始化成功率图表
     */
    initSuccessChart() {
        if (!this.successChart) return;
        
        const option = {
            title: {
                text: '成功率趋势',
                left: 'center',
                textStyle: {
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'axis',
                formatter: '{b}: {c}%'
            },
            xAxis: {
                type: 'category',
                data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                axisLabel: {
                    fontSize: 10
                }
            },
            yAxis: {
                type: 'value',
                name: '成功率(%)',
                nameTextStyle: {
                    fontSize: 10
                },
                axisLabel: {
                    fontSize: 10
                },
                min: 0,
                max: 100
            },
            series: [{
                name: '成功率',
                type: 'line',
                data: [95, 92, 98, 96, 94, 97, 99],
                smooth: true,
                itemStyle: {
                    color: '#5FB878'
                },
                lineStyle: {
                    width: 2
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(95, 184, 120, 0.3)' },
                        { offset: 1, color: 'rgba(95, 184, 120, 0.1)' }
                    ])
                }
            }]
        };
        
        this.successChart.setOption(option);
    }
    
    /**
     * 初始化表格
     */
    initTable() {
        if (typeof layui !== 'undefined') {
            layui.use(['table'], function() {
                var table = layui.table;
                
                this.historyTable = table.render({
                    elem: '#historyTable',
                    data: this.generateHistoryData(),
                    page: true,
                    limit: 10,
                    limits: [10, 20, 50, 100],
                    toolbar: true,
                    defaultToolbar: ['filter', 'exports', 'print'],
                    done: function(res, curr, count) {
                        console.log('历史表格渲染完成', res, curr, count);
                    }
                });
            }.bind(this));
        }
    }
    
    /**
     * 生成历史数据
     */
    generateHistoryData() {
        const data = [];
        const servers = ['server1.example.com', 'server2.example.com', 'server3.example.com', 'server4.example.com'];
        const types = ['VMess', 'VLESS', 'Trojan', 'Shadowsocks'];
        const statuses = ['成功', '失败', '超时'];
        
        for (let i = 0; i < 20; i++) {
            const time = new Date(Date.now() - i * 5 * 60 * 1000);
            const status = statuses[Math.floor(Math.random() * statuses.length)];
            const latency = status === '成功' ? Math.floor(Math.random() * 200) + 50 : 0;
            
            data.push({
                time: this.formatDateTime(time),
                server: servers[Math.floor(Math.random() * servers.length)],
                type: types[Math.floor(Math.random() * types.length)],
                status: status,
                latency: latency,
                result: status === '成功' ? '解析成功' : '解析失败',
                operation: '<button class="layui-btn layui-btn-xs layui-btn-primary" onclick="viewDetails(' + i + ')">详情</button>'
            });
        }
        
        return data;
    }
    
    /**
     * 格式化日期时间
     */
    formatDateTime(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    
    /**
     * 绑定事件
     */
    bindEvents() {
        const self = this;
        
        // 监听表单提交
        layui.use(['form'], function() {
            var form = layui.form;
            
            form.on('submit(resolve-btn)', function(data) {
                self.startResolve(data.field);
                return false;
            });
            
            form.on('submit(test-btn)', function(data) {
                self.testConnection(data.field);
                return false;
            });
            
            form.on('submit(copy-btn)', function() {
                self.copyConfiguration();
                return false;
            });
            
            // 监听解析类型变化
            form.on('radio(resolveType)', function(data) {
                self.updateFormFields(data.value);
            });
            
            // 监听传输协议变化
            form.on('select(transport)', function(data) {
                self.toggleTransportFields(data.value);
            });
        });
        
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            if (this.chart) this.chart.resize();
            if (this.latencyChart) this.latencyChart.resize();
            if (this.successChart) this.successChart.resize();
        });
    }
    
    /**
     * 开始解析 - 移除模拟数据
     */
    startResolve(params) {
        console.log('开始解析:', params);
        
        const resultDiv = document.getElementById('resolve-result');
        resultDiv.innerHTML = `
            <div class="result-loading">
                <i class="layui-icon layui-icon-loading layui-anim-rotate"></i>
                <p>正在解析中...</p>
            </div>
        `;
        
        // 模拟解析过程已移除
        setTimeout(() => {
            resultDiv.innerHTML = `
                <div class="result-info">
                    <i class="layui-icon layui-icon-tips"></i>
                    <h4>解析功能需要连接真实数据接口</h4>
                    <p>请配置后端解析服务</p>
                </div>
            `;
        }, 2000);
    }
    
    /**
     * 测试连接 - 移除模拟数据
     */
    testConnection(params) {
        console.log('测试连接:', params);
        
        layui.use(['layer'], function() {
            var layer = layui.layer;
            layer.msg('测试连接功能需要连接真实数据接口', {icon: 5});
        });
    }
    
    /**
     * 复制配置
     */
    copyConfiguration() {
        const config = this.generateConfiguration();
        
        if (navigator.clipboard) {
            navigator.clipboard.writeText(config).then(() => {
                layui.use(['layer'], function() {
                    var layer = layui.layer;
                    layer.msg('配置已复制到剪贴板', {icon: 1});
                });
            }).catch(() => {
                this.fallbackCopy(config);
            });
        } else {
            this.fallbackCopy(config);
        }
    }
    
    /**
     * 备用复制方法
     */
    fallbackCopy(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        
        layui.use(['layer'], function() {
            var layer = layui.layer;
            layer.msg('配置已复制到剪贴板', {icon: 1});
        });
    }
    
    /**
     * 生成配置
     */
    generateConfiguration() {
        const formData = layui.form.val('v2-resolve-form');
        
        return JSON.stringify({
            protocol: formData.resolveType,
            address: formData.serverAddress,
            port: parseInt(formData.serverPort),
            userId: formData.userId,
            alterId: parseInt(formData.alterId),
            transport: formData.transport,
            wsPath: formData.wsPath,
            tls: formData.tls ? true : false
        }, null, 2);
    }
    
    /**
     * 更新表单字段
     */
    updateFormFields(type) {
        // 根据类型显示/隐藏字段
        const wsPathGroup = document.getElementById('ws-path-group');
        
        if (type === 'trojan') {
            wsPathGroup.style.display = 'none';
        }
    }
    
    /**
     * 切换传输协议字段
     */
    toggleTransportFields(transport) {
        const wsPathGroup = document.getElementById('ws-path-group');
        
        if (transport === 'ws') {
            wsPathGroup.style.display = 'block';
        } else {
            wsPathGroup.style.display = 'none';
        }
    }
    
    /**
     * 更新图表 - 移除模拟数据
     */
    updateCharts() {
        // 图表更新功能需要连接真实数据接口
        console.log('图表更新功能需要连接真实数据接口');
    }
    
    /**
     * 添加到历史记录 - 移除模拟数据
     */
    addToHistory(params, status) {
        // 历史记录功能需要连接真实数据接口
        console.log('历史记录功能需要连接真实数据接口');
    }
    
    /**
     * 加载历史数据
     */
    loadHistoryData() {
        // 历史数据已在初始化时加载
    }
    
    /**
     * 清理资源
     */
    destroy() {
        console.log('V2解析组件销毁');
        
        // 销毁图表
        if (this.chart) {
            this.chart.dispose();
            this.chart = null;
        }
        
        if (this.latencyChart) {
            this.latencyChart.dispose();
            this.latencyChart = null;
        }
        
        if (this.successChart) {
            this.successChart.dispose();
            this.successChart = null;
        }
        
        // 清理事件监听
        window.removeEventListener('resize', this.resizeCharts);
    }
}

// 注册到全局视图组件
if (!window.ViewComponents) {
    window.ViewComponents = {};
}
window.ViewComponents.v2Resolve = V2ResolveView;